package features.advance.leetcode.string.easy;

import java.util.HashMap;
import java.util.Map;

/**
 * @author LIN
 * @date 2023-08-23 20:13
 * 290. 单词规律
 * 简单
 * 给定一种规律 pattern 和一个字符串 s ，判断 s 是否遵循相同的规律。
 *
 * 这里的 遵循 指完全匹配，例如， pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。
 *
 *
 *
 * 示例1:
 *
 * 输入: pattern = "abba", s = "dog cat cat dog"
 * 输出: true
 * 示例 2:
 *
 * 输入:pattern = "abba", s = "dog cat cat fish"
 * 输出: false
 * 示例 3:
 *
 * 输入: pattern = "aaaa", s = "dog cat cat dog"
 * 输出: false
 *
 *
 * 提示:
 *
 * 1 <= pattern.length <= 300
 * pattern 只包含小写英文字母
 * 1 <= s.length <= 3000
 * s 只包含小写英文字母和 ' '
 * s 不包含 任何前导或尾随对空格
 * s 中每个单词都被 单个空格 分隔
 * 集合论里的双射
 */
public class Solution290 {

    public static void main(String[] args) {
        Solution solution = new Solution() {
            @Override
            public boolean wordPattern(String pattern, String str) {
                Map<String, Character> str2ch = new HashMap<String, Character>();
                Map<Character, String> ch2str = new HashMap<Character, String>();
                int m = str.length();
                int i = 0;
                for (int p = 0; p < pattern.length(); ++p) {
                    char ch = pattern.charAt(p);
                    if (i >= m) {
                        return false;
                    }
                    int j = i;
                    while (j < m && str.charAt(j) != ' ') {
                        j++;
                    }
                    String tmp = str.substring(i, j);
                    if (str2ch.containsKey(tmp) && str2ch.get(tmp) != ch) {
                        return false;
                    }
                    if (ch2str.containsKey(ch) && !tmp.equals(ch2str.get(ch))) {
                        return false;
                    }
                    str2ch.put(tmp, ch);
                    ch2str.put(ch, tmp);
                    i = j + 1;
                }
                return i >= m;
            }
        };
        String pattern = "aaa";
        String s = "dog dog dog dog dog";
        System.out.println(solution.wordPattern(pattern, s));

    }

    static class Solution {
        public boolean wordPattern(String pattern, String s) {
            // System.out.println(pattern+"  "+s);
            char[] arr = pattern.toCharArray();
            Map<Object,Object> map = new HashMap<>(16);
            String[] arr1 = s.split(" ");

            if(arr1.length != arr.length){
                return false;
            }
            for(int i=0;i<arr.length;i++){

                // System.out.println(arr[i]);

                Object obj = map.put(arr[i],arr1[i]);

                if(obj!=null && !arr1[i].equals(obj)){
                    return false;
                }
                Object obj1 = map.put(arr1[i],arr[i]);
                if(obj1!=null && !arr1[i].equals(obj)){
                    return false;
                }
            }
            return true;
        }
    }
}
